package com.itstyle.seckill.topic.diruptor;

import com.itstyle.seckill.queue.disruptor.SeckillEvent;
import com.itstyle.seckill.queue.disruptor.SeckillEventProducer;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

import java.util.concurrent.ThreadFactory;

/**
 * @Auther: liuwenxiang
 * @Date: 2020/4/3 16:17
 * @Description:
 */
public class DisruptorUtil {

    /**
     * 1。创建Disruptor，注入事件工厂，线程工厂，设置环大小
     * 2。为Disruptor绑定消费者，启动Disruptor，消费者异步消费。
     * 3。在Disruptor上获取ringBuffer，向ringBuffer中添加事件。
     */
    private  static  Disruptor<LongEvent> disruptor =null;
    static {

        LongEventFactory longEventFactory =new LongEventFactory();

        ThreadFactory threadFactory =new ThreadFactory(){

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        };
        disruptor =new Disruptor<LongEvent>(longEventFactory,20,threadFactory);
        disruptor.handleEventsWith(new LongEventHandler());
        disruptor.start();
    }


    public static void produce(LongEvent longEvent){
        RingBuffer<LongEvent> ringBuffer =  disruptor.getRingBuffer();
        LongEventProducer longEventProducer =new LongEventProducer(ringBuffer);
        longEventProducer.publish(longEvent.getUserId(),longEvent.getLog());
    }

    public static void main(String[] args) {

    }
}
